package com.mo.handler;

import com.auth0.jwt.exceptions.*;
import com.mo.common.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Result exception(Exception e) {
        e.printStackTrace();

        // 判断具体的异常类型
        if (e instanceof AlgorithmMismatchException) {
            return Result.error("算法不匹配: " + e.getMessage(), HttpServletResponse.SC_BAD_REQUEST);
        } else if (e instanceof IncorrectClaimException) {
            return Result.error("声明不正确: " + e.getMessage(), HttpServletResponse.SC_BAD_REQUEST);
        } else if (e instanceof InvalidClaimException) {
            return Result.error("无效声明: " + e.getMessage(), HttpServletResponse.SC_BAD_REQUEST);
        } else if (e instanceof JWTCreationException) {
            return Result.error("JWT创建失败: " + e.getMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } else if (e instanceof JWTDecodeException) {
            return Result.error("JWT解析失败: " + e.getMessage(), HttpServletResponse.SC_BAD_REQUEST);
        } else if (e instanceof JWTVerificationException) {
            return Result.error("JWT验证失败: " + e.getMessage(), HttpServletResponse.SC_UNAUTHORIZED);
        } else if (e instanceof MissingClaimException) {
            return Result.error("缺失声明: " + e.getMessage(), HttpServletResponse.SC_BAD_REQUEST);
        } else if (e instanceof SignatureGenerationException) {
            return Result.error("签名生成失败: " + e.getMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } else if (e instanceof SignatureVerificationException) {
            return Result.error("签名验证失败: " + e.getMessage(), HttpServletResponse.SC_UNAUTHORIZED);
        } else if (e instanceof TokenExpiredException) {
            return Result.error("Token已过期: " + e.getMessage(), HttpServletResponse.SC_UNAUTHORIZED);
        } else {
            // 其他未知的异常
            return Result.error("未知错误: " + e.getMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
